#!/usr/bin/python

# ==============================
# loadVirusFiles.py
# ===============================
import os,os.path,subprocess,logging,shlex,sys,datetime
 
startingDir = os.getcwd() # save our currentdirectory
print(startingDir)
root ='/home/ubuntu/virus-data/processed-data'

log = logging.getLogger('loadVirusFiles')
fh = logging.FileHandler('loadVirusFiles.log')
log.addHandler(fh)
log.setLevel(logging.INFO)
mylog = logging.getLogger('loadVirusFiles').handlers[0].stream

startTime = datetime.datetime.now()


# ====================
# load VirusTypeFile
# ====================
for filename in os.listdir(root):
    #print 'filename = ' +filename
    if os.path.isfile(root + '/' + filename):
      if filename.endswith('.xml') and filename.startswith('VirusTypes_'):
        cmd=  'java  -jar /home/ubuntu/git/virus-catalog/Java/VirusCatalog2.jar -VirusTypeFile ' + root + '/' + filename
        print('Running ' + cmd)
        log.info('Running ' + cmd)
        p = subprocess.Popen(shlex.split(cmd),stdout=mylog)
        # if you don't wait(), the output won't be necessarily in chronological order.
        r = p.wait()
        # write a last test line to the log
        log.info('loaded virus types: %s'% r)
        os.rename(root + '/' + filename, root + '/done/' + filename)

# ===================
# load VirusFiles
# ===================
print('root = ' + root)
count = 0
for filename in os.listdir(root):
    count += 1
    if count > 400:
        stopTime = datetime.datetime.now()
        print ''
        print 'Processing time = ' + str(stopTime - startTime)
        print ''
        exit(0)

    print 'filename = ' +filename
    if os.path.isfile(root + '/' + filename):   
      if filename.endswith('.xml') and (filename.startswith('Virus_') or filename.startswith('Bitdefender_')):
        fullpath = os.path.join(root,filename)
        print('processing filename: ' + filename)

        cmd=  'java  -jar /home/ubuntu/git/virus-catalog/Java/VirusCatalog2.jar -VirusFile ' + root + '/' + filename
        print('Running ' + cmd)
        log.info('Running ' + cmd)
        print('== STARTING ====================')
        p = subprocess.Popen(shlex.split(cmd),stdout=mylog)
        # if you don't wait(), the output won't be necessarily in chronological order.
        r = p.wait()
        # write a last test line to the log
        log.info('done %s'% r)
        # os.system(cmd)
        print('== FINISHING ===================')      
        os.rename(root + '/' + filename, root + '/done/' + filename)


stopTime = datetime.datetime.now()

print ''
print 'Processing time = ' + str(stopTime - startTime)
print ''





